#!/bin/bash

set -e

ISO_DIR="/coreos"
DEST_DIR="$1"

if [ ! -d "${DEST_DIR}" ]; then
    mkdir -p "${DEST_DIR}"
fi

copy_if_needed() {
    local source="$1"
    local dest_file

    dest_file="${DEST_DIR}/$(basename "${source}")"

    if [ -f "${dest_file}" ] && [ "$(cat "${dest_file}.sha256")" = "$(cat "${source}.sha256")" ]; then
        echo "${dest_file} is already up to date" >&2
    else
        rm -f "${dest_file}.sha256"
        echo "Extracting ISO file" >&2
        if [ -n "${IP_OPTIONS:-}" ]; then
            echo "Adding kernel argument ${IP_OPTIONS}" >&2
            uswift-installer iso kargs modify -a "${IP_OPTIONS}" -o "${dest_file}" "${source}"
        else
            cp "${source}" "${DEST_DIR}"
            echo "${dest_file}"
        fi
        cp "${source}.sha256" "${DEST_DIR}"
    fi
}

for iso in "${ISO_DIR}"/*.iso; do
    copy_if_needed "${iso}"
done
